<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addDel">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="item.uname">
          <td>{{ index + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="del(item.uname)">删除</button>
            <button @click="reset(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr: [
        {
          uname: '武松',
          age: '34',
          sex: '男',
        },
        {
          uname: '宋江',
          age: '40',
          sex: '男',
        },
      ],
      uname: '',
      age: '',
      sex: '',
      flag: true,
      num: '',
    }
  },
  methods: {
    addDel() {
      if (this.uname && this.age) {
        if (this.flag) {
          const obj = {
            uname: this.uname,
            age: this.age,
            sex: this.sex,
          }
          this.arr.push(obj)
          this.age = ''
          this.uname = ''
          this.sex = ''
        } else {
          this.arr.splice(this.num, 1, {
            uname: this.uname,
            age: this.age,
            sex: this.sex,
          })
          this.age = ''
          this.uname = ''
          this.sex = ''
          this.flag = true
        }
      } else {
        alert('输入错误')
      }
    },
    del(date) {
      this.arr = this.arr.filter((item) => item.uname != date)
      this.age = ''
      this.uname = ''
      this.sex = ''
      this.flag = true
    },
    reset(date) {
      this.age = this.arr[date].age
      this.uname = this.arr[date].uname
      this.sex = this.arr[date].sex
      this.num = date
      this.flag = false
    },
  },
  computed: {},
}
</script>
